package org.rency.mq.activemq.listener.handler.impl;

import org.rency.mq.activemq.listener.handler.MessageHandlerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class MessageHandlerFactoryImpl implements MessageHandlerFactory {
	private static Logger logger = LoggerFactory.getLogger(MessageHandlerFactoryImpl.class);
	private static MessageHandlerFactory factory = new MessageHandlerFactoryImpl();

	private ConcurrentMap<String, AbstractMessageHandler> messageHandlers = new ConcurrentHashMap<String, AbstractMessageHandler>();

	private MessageHandlerFactoryImpl() {
	}

	public static MessageHandlerFactory getInstance() {
		return factory;
	}

	public void addMessageHandler(String destination,
			AbstractMessageHandler messageHandler) {
		if (messageHandler == null)
			throw new IllegalArgumentException(
					"Message handler cannot be null.");

		this.messageHandlers.putIfAbsent(destination, messageHandler);
	}

	public AbstractMessageHandler getMessageHandler(String destination) {
		logger.info("Get message handler, destination is: {}.",destination);
		if (!StringUtils.hasText(destination)) {
			throw new IllegalArgumentException("Handler class name cannot be empty.");
		}
		return this.messageHandlers.get(destination);
	}
}
